/*
 * @Author: Li
 * @Date: 2022-04-03 13:44:52
 * @LastEditors: Li
 * @LastEditTime: 2022-04-04 17:17:47
 * @Description: 
 */
// https://api.apidoc.doyzheng.com/user/get
// https://api.apidoc.doyzheng.com/project/list
// https://api.apidoc.doyzheng.com/project/join-list
// https://api.apidoc.doyzheng.com/category/list
// https://api.apidoc.doyzheng.com/dictionary/detail
// https://api.apidoc.doyzheng.com/api/list

// yl-cli config set account 19137804785;
// yl-cli config set password li111111;
// yl-cli doc module(班课练习) catagroy(订单) api(MCU5001) all;

const HOST = 'https://api.apidoc.doyzheng.com';
import axios from 'axios';
import { 
	generateApiOptionsCode, 
	generateApiOptionsFilename 
} from "../utils/generate-api-options-code.js";
import { 
	generateApiCode, 
	generateApiFilename 
} from "../utils/generate-api-code.js";
import { exec as login } from "./login.js";
import { cache } from "../utils/cache.js";
import fs from 'fs';
const API_LIST = [];

function projectList() {
  return axios.post(`${HOST}/project/list`, {
      limit: 999
    },{
      headers: {
        token: cache('token'),
      }
    }).then(({ data: { data: { list } } }) => {
      cache('debug') && console.log('项目列表', list);
      return list || [];
    })
    .catch((err) => {
      console.error(err);
    });
}

function projectJoinList() {
  return axios.post(`${HOST}/project/join-list`, {
      limit: 999
    },{
      headers: {
        token: cache('token'),
      }
    }).then(({ data: { data: { list } } }) => {
      cache('debug') && console.log('参加项目列表', list);
      return list || [];
    })
    .catch((err) => {
      console.error(err);
    });
}

function categoryList(project_code) {
  return axios.post(`${HOST}/category/list`, {
      limit: 999,
      project_code: project_code
    },{
      headers: {
        token: cache('token'),
      }
    })
    .catch((err) => {
      console.error(err);
    });
}

function apiList(project_code) {
  return axios.post(`${HOST}/api/list`, {
      limit: 9999,
      project_code: project_code
    },{
      headers: {
        token: cache('token'),
      }
    })
    .catch((err) => {
      console.error(err);
    });
}

function apiDetail(id) {
  return axios.post(`${HOST}/api/detail`, {
      id: id
    },{
      headers: {
        token: cache('token'),
      }
    })
    .catch((err) => {
      console.error(err);
    });
}

function exec(cmds, path) {
  const project = cmds.shift();
  if (project === undefined) {
    return console.warn('请输入项目');
  }
  const catagroy = cmds.shift();
  if (catagroy === undefined) {
    return console.warn('请输入分类');
  }
  const apiName = cmds.shift();

  let p;
  let c;

  login().then(() => {
    return Promise.allSettled([projectList(), projectJoinList()]);
  }).then((res) => {
    cache('debug') && console.log('项目-res', res);
    p = res.map((item) => item.value)
                  .flat(Number.POSITIVE_INFINITY)
                  .find((item) => item.project_name === project);
    if (p === undefined) {
      return Promise.reject(`${project}-项目不存在`);
    }
    cache('debug') && console.log('项目', p);
    return categoryList(p.project_code);
  }).then(({ data: { data: { list } } }) => {
    if (!list) {
      return Promise.reject(`${project}--分类为空`);
    }
    c = list.find(item => item.category_name === catagroy);
    if (c === undefined) {
      return Promise.reject(`${catagroy}--分类不存在`);
    }
    cache('debug') && console.log('分类', c);
    cache('debug') && console.log('categoryList', list);
    return apiList(p.project_code);
  }).then(({ data: { data: { list } } }) => {
    cache('debug') && console.log('apiList', list);
    if (!list) {
      return Promise.reject(`${project}--未登记api`);
    }
    return list.filter((item) => {
      return item.project_id === p.project_id && item.category_id === c.category_id;
    });
  }).then((res) => {
    API_LIST.splice(0, API_LIST.length, ...res);
    cache('debug') && console.log('开始下载');
    return Promise.allSettled(res.filter((item) => {
      if (apiName === undefined) {
        return true;
      } else if (apiName === 'both') {
        return true;
      } else if (apiName === 'theirs') {
        return true;
      } else if (apiName === 'mine') {
        return true;
      }
      return item.url === apiName || item.number_no === apiName || item.alias === apiName || item.name === apiName;
    }).map((item) => apiDetail(item.id)));
  }).then((res) => {
    const apiDetailArr = res.map((item) => item.value.data.data);
    const t = (apiName === 'both' || apiName === 'theris' || apiName === 'mine') ? apiName : 'both';
    cache('debug') && console.log('更新方式:' + t);
    for (const apiDetail of apiDetailArr) {
      const api = API_LIST.find((item) => item.id === apiDetail.id);
      const fileName = generateApiOptionsFilename(api);
      const content = generateApiOptionsCode(api);
      try {
        const filePath = `${ path }/${ fileName }`;
        // all 全部
        // theris 只更新他们有的
        // mine 更新我有的
        if (fs.existsSync(filePath)) {
          if (t === 'mine' || t === 'both') {
            fs.writeFileSync(filePath, content);
            console.log(filePath);
            console.log(fileName);
          }
        } else {
          if (t === 'theris' || t === 'both') {
            fs.writeFileSync(filePath, content);
            console.log(filePath);
            console.log(fileName);
          }
        }
      } catch (err) {
        console.error(err)
      }

      try {
        const fileName = generateApiFilename(api);
        const content = generateApiCode(api, apiDetail);
        const filePath = `${ path }/${ fileName }`;
        console.log(filePath);
        console.log(fileName);
        if (fs.existsSync(filePath)) {
          if (t === 'mine' || t === 'both') {
            fs.writeFileSync(filePath, content);
            cache('debug') && console.log(fileName);
          }
        } else {
          if (t === 'theris' || t === 'both') {
            fs.writeFileSync(filePath, content);
            cache('debug') && console.log(fileName);
          }
        }
      } catch (err) {
        console.error(err)
      }
    }
    cache('debug') && console.log('下载完毕');
  }).catch((err) => {
    console.error(err);
  });
}

export {
    exec
}
